package com.wzw.shoppingcart.service.impl;

import com.wzw.shoppingcart.entity.*;
import com.wzw.shoppingcart.service.DiscountService;
import com.wzw.shoppingcart.service.ProductService;
import com.wzw.shoppingcart.service.DiscountPromotionService;
import com.wzw.shoppingcart.service.PromotionService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.wzw.shoppingcart.constant.Constant.GIFT_BUY_DISCOUNT;
import static com.wzw.shoppingcart.constant.Constant.GIFT_SPLIT;

/**
 *@author wzw
 * 2023/4/15
 */
@Service
@Slf4j
@Setter(onMethod_ ={@Autowired} )
public class GiftDiscountServiceImplDiscount implements DiscountPromotionService {

    private DiscountService discountService;
    private PromotionService promotionService;
    private ProductService productService;

    @Override
    public BigDecimal calculateDiscount(List<CartLine> cartLines, BigDecimal totalOriginPrice) {

        List<Product> productList = promotionService.promotionProduct(cartLines, GIFT_BUY_DISCOUNT);

        Discount discount = discountService.getByType(GIFT_BUY_DISCOUNT);
        Integer conditionAmount = discount.getConditionAmount();

        if (productList.size()<conditionAmount){
            return BigDecimal.ZERO;
        }

        String[] giftIds = discount.getGifts().split(GIFT_SPLIT);

        Arrays.stream(giftIds)
                .map(Integer::parseInt)
                .map(productService::getById)
                .forEach(p->{
                    p.setDiscountPrice(BigDecimal.ZERO);
                    CartLine cartLine = new CartLine();
                    cartLine.setProduct(p);
                    cartLine.setProductCount(1);
                    cartLine.setProductId(p.getProductId());
                    cartLine.setIsGift(true);
                    cartLines.add(cartLine);
                });

    return BigDecimal.ZERO;
    }
}
